%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import cm
import ipyparallel as ipp
from time import time
from datetime import datetime
import motif as mf
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.decomposition import PCA
from sklearn.utils import shuffle
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.model_selection import train_test_split, cross_val_score, cross_validate
from scipy.stats import spearmanr
from scipy.stats import pearsonr
Intel(R) Extension for Scikit-learn* enabled (https://github.com/intel/scikit-learn-intelex)
### set parameters for the motif analysis
PROTEIN_NAME = 'Klf9'
PROT_CONC = 0.1 # free protein concentration at binding reation; PBM typically 0.1 and RNACompete typically 0.002
BOTH_STRANDS = True # wheter both strands are present for binding; True if double-stranded DNA or RNA is used as probes
#TIME_DISS = 1800 # experimental time span after binding reaction during which dissociation of the protein from the probe was possible
STAGES=mf.stage(protein=PROTEIN_NAME)
### read data
## RNAcompete sample data
#dfprobes_raw=pd.read_excel('./data/RNAcompete/A2BP1.xlsx')
#dfprobes_raw=pd.read_excel('./data/RNAcompete/HNRNPA1.xlsx')
#dfprobes_raw=pd.read_excel('./data/RNAcompete/PTBP1.xlsx')
#dfprobes_raw=pd.read_excel('./data/RNAcompete/RBM24.xlsx')
#dfprobes_raw=pd.read_csv('./data/samplePBMs/Mlx__pTH2882_HK.raw', sep='\t')
dfprobes_raw=pd.read_csv('./data/samplePBMs/Klf9__pTH2353_HK.raw', sep='\t')
#dfprobes_raw=pd.read_csv('./data/samplePBMs/Prdm11__pTH3455_HK.raw', sep='\t')
#dfprobes_raw=pd.read_csv('./data/samplePBMs/Sox10__pTH1729_HK.raw', sep='\t')
print('Columns of imported Data File: %s' % dfprobes_raw.columns)
#dfprobes_raw.describe()
#dfprobes_raw.info()
Columns of imported Data File: Index(['#id_spot', 'row', 'col', 'control', 'id_probe', 'pbm_sequence',
'linker_sequence', 'mean_signal_intensity', 'mean_background_intensity',
'flag'],
dtype='object')
### select columns for probe sequence and signal
column_sequence = 'pbm_sequence'
column_signal = 'mean_signal_intensity'
background_signal = 'mean_background_intensity' #set to None if not needed
#background_signal=None
#basic preprocessing
dfprobes_raw[column_signal] = dfprobes_raw[column_signal].apply(
lambda a: np.NaN if a == ' ' else a)
dfprobes_raw[column_signal] = dfprobes_raw[column_signal].apply(
lambda a: np.NaN if a == '' else a)
dfprobes_raw[column_sequence] = dfprobes_raw[column_sequence].apply(
lambda a: np.NaN if str(a).lower() == 'nan' else a)
dfprobes_raw[column_sequence] = dfprobes_raw[column_sequence].apply(
lambda a: np.NaN if a == '' else a)
dfprobes_raw = dfprobes_raw.dropna()
#construct new dataframe with only necessary data
if type(background_signal) == type(None):
dfprobes = pd.DataFrame({
'seq':
dfprobes_raw[column_sequence].astype(str),
'signal binding':
dfprobes_raw[column_signal].astype(np.float32)
}) #rebuild dataframe
else:
dfprobes = pd.DataFrame({
'seq':
dfprobes_raw[column_sequence].astype(str),
'signal':
dfprobes_raw[column_signal].astype(np.float32),
'background':
dfprobes_raw[background_signal].astype(np.float32)
}) #rebuild dataframe
dfprobes['signal binding'] = dfprobes['signal'] - dfprobes['background']
dfprobes = dfprobes.dropna()
# display main properties of data set
dfprobes['signal binding'].plot(figsize=(15, 5))
dfprobes.describe()
### check type of nucleic acid
dfprobes['seq'] = dfprobes['seq'].apply(
lambda seq: seq.upper().replace(" ", "")) #upper and remove blanks
dfprobes['RNA'] = dfprobes['seq'].apply(
lambda seq: all(char in 'ACGU' for char in seq))
dfprobes['DNA'] = dfprobes['seq'].apply(
lambda seq: all(char in 'ACGT' for char in seq))
non_RNA_counts = len(dfprobes[dfprobes['RNA'] == False])
non_DNA_counts = len(dfprobes[dfprobes['DNA'] == False])
if non_RNA_counts < non_DNA_counts:
NUC_TYPE = 'RNA'
print('I: RNA probes detected!')
else:
NUC_TYPE = 'DNA'
print('I: DNA probes detected!')
if NUC_TYPE == 'RNA' and non_RNA_counts != 0:
print(
'E: The probe sequences appear to be RNA, however there are some non-RNA nucleotides in the sequences.'
)
print('E: Please check the following sequnces %s' %
dfprobes[dfprobes['RNA'] == False])
if NUC_TYPE == 'DNA' and non_DNA_counts != 0:
print(
'E: The probe sequences appear to be RNA, however there are some non-RNA nucleotides in the sequences.'
)
print('E: Please check the following sequnces %s' %
dfprobes[dfprobes['DNA'] == False])
I: DNA probes detected!
### option to add a constant sequence at the 3' end and 5' end
sequence_to_be_added_5 = ''
sequence_to_be_added_3 = 'CCTGT' # standard PBM arrays: CCTGTGTGAAATTGTTATCCGCTCT T7 array: GTCTTGA..
dfprobes['seq'] = sequence_to_be_added_5.upper(
) + dfprobes['seq'] + sequence_to_be_added_3.upper()
print(
f"I: The nucleotide sequence {sequence_to_be_added_5.upper()} has been added to the 5' end all probe sequences."
)
print(
f"I: The nucleotide sequence {sequence_to_be_added_3.upper()} has been added to the 3' end all probe sequences."
)
I: The nucleotide sequence has been added to the 5' end all probe sequences. I: The nucleotide sequence CCTGT has been added to the 3' end all probe sequences.
### egalize length
dfprobes['seq_length'] = dfprobes['seq'].apply(len)
if max(dfprobes['seq_length']) != min(dfprobes['seq_length']):
print('I: Probes length is not uniform, detected range: %i ..%i' %
(min(dfprobes['seq_length']), max(dfprobes['seq_length'])))
max_length = max(dfprobes['seq_length'])
dfprobes['padded_sequence'] = dfprobes['seq'].apply(
lambda seq: seq + ((max_length - len(seq)) * '-'))
print(
"I: Probe sequences have been padded at the 5' to the uniform length of %i nucleotides"
% max_length)
else:
print('I: Probe sequences have the uniform length of %i nucleotides' %
(dfprobes['seq_length'].median()))
dfprobes['padded_sequence'] = dfprobes['seq']
print('I: Total datasets contains %i sequences.' % len(dfprobes))
# visualize composition of each position
df_nucleotides = mf.split_sequence_in_nucleotides(dfprobes['padded_sequence'])
dfcount = pd.DataFrame(index=['A', 'C', 'G', 'T', 'U', '-'])
for column in df_nucleotides:
dfcount[column] = df_nucleotides[column].value_counts()
dfcount = dfcount.fillna(0) #zeros for NaN
dfcount.transpose().plot(figsize=(15, 5), kind='bar')
print('I: Visualisation of the base composition per position')
print(
'I: If positions are invariant they can be removed before sequence analysis.'
)
I: Probes length is not uniform, detected range: 36 ..40 I: Probe sequences have been padded at the 5' to the uniform length of 40 nucleotides I: Total datasets contains 40330 sequences. I: Visualisation of the base composition per position I: If positions are invariant they can be removed before sequence analysis.
# You may remove invariant continuos positions by adjusting the slicing.
# It is recommended to leave a few invariant positions to allow for binding events
# between the variable and constant part of the probes.
dfprobes['padded_sequence'] = dfprobes['padded_sequence'].apply(lambda s: s[:38]) ### <==== do the slicing here
# visualize composition of each position
print('I: Visualisation of the base composition per position after slicing.')
df_nucleotides = mf.split_sequence_in_nucleotides(dfprobes['padded_sequence'])
dfcount = pd.DataFrame(index=['A', 'C', 'G', 'T', 'U', '-'])
for column in df_nucleotides:
dfcount[column] = df_nucleotides[column].value_counts()
dfcount = dfcount.fillna(0) #zeros for NaN
dfcount.transpose().plot(figsize=(15, 5), kind='bar')
plt.show()
# preparation for later classification
mean = dfprobes['signal binding'].mean()
std = dfprobes['signal binding'].std()
THRESHOLD = mean + 4 * std #4*std used according to Weirauch et al., 2013
dfprobes['positive probe'] = dfprobes['signal binding'].apply(
lambda s: True if s > THRESHOLD else False)
print(
'I: The whole dataset has been used to set the threshold for a positive probe.'
)
print('I: The threshold is %f' % THRESHOLD)
print(
f"I: {len(dfprobes[dfprobes['positive probe']])} probes of {len(dfprobes)} are above threshold."
)
if len(dfprobes[dfprobes['positive probe']]) == 0:
print(
'E: No probe above THRESHOLD. Classification is not possible. Please adjust the THRESHOLD.'
)
I: Visualisation of the base composition per position after slicing.
I: The whole dataset has been used to set the threshold for a positive probe. I: The threshold is 27352.791992 I: 567 probes of 40330 are above threshold.
#### Shuffle and prepare dataset for training and testing
# shuffle and split
dfprobes = shuffle(dfprobes)
dftrain, dftest = train_test_split(dfprobes, test_size=0.2)
print(
'I: The whole dataset has been split in training (80%) and test (20%) datasets.'
)
# display histogramms of test and training set
dftrain['signal binding'].plot(kind='hist', bins=25).axvline(x=THRESHOLD, color='r', linestyle='-.', lw=0.5, label='threshold classification')
dftest['signal binding'].plot(kind='hist', bins=25)
plt.show()
# generate a subset with maximal 1000 probes
downsampled_size = 1000 # You may change downsampled size here.
percentile = 0.5 * downsampled_size / len(
dftrain
) * 100 #percentile required for lowest and highest to achieve down-sampled size
if percentile < 4:
percentile = 4 #do not use only the extreme values
elif percentile > 10:
percentile = 10 #avoid taking value from the mid-range
if len(dftrain) * percentile * 2 / 100 < downsampled_size / 4:
print('W: The subset only contains %i probes - a rather low number.' %
dftrain * percentile * 2 / 100)
print(
'I: A downsampled dataset containing the lowest and highest %.1f %% of the dataset is generated.'
% percentile)
dfsubset_high = dftrain[dftrain['signal binding'] >= dftrain['signal binding'].quantile(1 - percentile / 100)] # highest part
dfsubset_low = dftrain[dftrain['signal binding'] <= dftrain['signal binding'].quantile(percentile / 100)] # lowest part
print('I: Median values of lowest and highest %.1f %%: %r %r' %
(percentile, dfsubset_low['signal binding'].quantile(0.5),
dfsubset_high['signal binding'].quantile(0.5)))
if len(dfsubset_high) + len(dfsubset_low) > downsampled_size:
print('I: The dataset is further downsampled to %i sequences.' %
downsampled_size)
dfsubset_high = dfsubset_high.sample(downsampled_size - int(downsampled_size / 2))
dfsubset_low = dfsubset_low.sample(int(downsampled_size / 2))
dfsubset = pd.concat([dfsubset_high, dfsubset_low])
else:
dfsubset = pd.concat([dfsubset_high, dfsubset_low])
dfsubset = shuffle(dfsubset)
# display main properties of downsampled data set
print('I: Histogramm of the downsampled dataset along the with classification threshold.')
dfsubset['signal binding'].plot(kind='hist', bins=25).axvline(x=THRESHOLD, color='r', linestyle='-.', lw=0.5, label='threshold classification')
plt.show()
# establish numpy arrays of the sequenc and binding data in the dataframes
# complete data
X=mf.hotencode_sequence(dfprobes['padded_sequence'], nuc_type=NUC_TYPE)
y=np.array(dfprobes['signal binding'])
# training set
X_train=mf.hotencode_sequence(dftrain['padded_sequence'], nuc_type=NUC_TYPE)
y_train=np.array(dftrain['signal binding'])
# subset of training set
X_subset=mf.hotencode_sequence(dfsubset['padded_sequence'], nuc_type=NUC_TYPE)
y_subset=np.array(dfsubset['signal binding'])
# test set
X_test=mf.hotencode_sequence(dftest['padded_sequence'], nuc_type=NUC_TYPE)
y_test=np.array(dftest['signal binding'])
I: The whole dataset has been split in training (80%) and test (20%) datasets.
I: A downsampled dataset containing the lowest and highest 4.0 % of the dataset is generated. I: Median values of lowest and highest 4.0 %: 643.771240234375 21367.48046875 I: The dataset is further downsampled to 1000 sequences. I: Histogramm of the downsampled dataset along the with classification threshold.
### perform a quick & dirty round for a short motif by fitting on subset to check data integrity
#fit regression quick_model
quick_model=mf.findmotif(motif_length=3, protein_conc=PROT_CONC, both_strands=BOTH_STRANDS, ftol=0.01)
start = time()
quick_model.fit(X_subset,y_subset)
print("I: Optimization took %.2f hours." % ((time() - start)/3600))
# print & display main results
quick_model.analyse_motif(X_subset,y_subset, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('quick', quick_model)
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
I: Optimization took 0.06 hours. I: energy matrix and logos:
A C G T
0 -15451 17539 11356 -13444
1 -3272 1701 -832 2403
2 1443 -3646 3145 -942
I: summed absolute energies of each position:
0 57791
1 8210
2 9178
dtype: int64
I: averaged summed energy over all positions: 25060
I: Mean and Standard Deviation for the Free Energy G to all subsequences of all probes: -4827 +/- 16012
I: Plot of the Occupancy of a subsite as the function of the Free Energy G
overlaid with the distribution of the Free Energy of all subsites.
I: There shall be only a small overlap of both curves. i.e. only the most negative Free Energies
lead to a measurable occupancy.
I: Calculated occupancy over all subsite of a single probe: binding: 0.06700 .. 0.67815 (ratio: 10.1) I: number of probes: 1000 I: Pearson Correlation r: 0.5278 I: mean absolute error: 9901.6968
WARNING:matplotlib.font_manager:findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans.
I: Classification performance AUROC: 0.7207
| stage | protein | # probes | motif length | r | AUROC | G0 | G0 fitted | ratio | max binding | min binding | energies | model | logo | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | quick | Klf9 | 1000 | 3 | 0.527776 | 0.720653 | -11473.366709 | False | 10.121019 | 0.678154 | 0.067004 | -15451,.. | suppressed |
#### Perfrom GridCV Search for exploration of the motif length goal: identify the minimum motif length which gives a good r-value
# optional: allow for global optimization to verify whether the local optimization is good enough
# not recommended include fitG0=True. This option should only be considered when the local optimization is started with an approximate motif and the start parameter is set
# not recommended set time_dissociation. The effect of dissociation should be only considered when the local optimization is started with an approximate motif.
# prepare grid search over motif_length
model_grid=mf.findmotif(protein_conc=PROT_CONC, both_strands=BOTH_STRANDS)
param_grid = {"motif_length": [3,4,5,6,7,8]} # choose sensible range for length of motif
# define custom refit function
def custom_refit(cv_results):
"""returns index of max r2/sqrt(motif_length)"""
df_grid=pd.DataFrame(cv_results)
index=(df_grid['mean_test_score']/(df_grid['param_motif_length'].apply(float).apply(np.sqrt))).idxmax()
return index
# run grid search and refit according to custom refit
grid_search = GridSearchCV(model_grid, param_grid=param_grid, verbose=2, cv=5, refit=custom_refit, n_jobs=-1)
start = time()
grid_search.fit(X_subset, y_subset)
print("I: GridSearchCV took %.2f hours for %d candidate parameter settings."
% ((time() - start)/3600, len(grid_search.cv_results_["params"])))
print('I: number of samples: %i' %len(X_subset))
df_grid=pd.DataFrame(grid_search.cv_results_)
print('I: Plot of r2 vs motif length and vs root(motif length)')
df_grid.rename(columns={'mean_test_score':'r2'}, inplace=True)
df_grid.plot(kind='scatter', x='param_motif_length', y='r2', yerr='std_test_score', figsize=(5,3)).set_xticks(param_grid["motif_length"])
df_grid['r2/sqrt(length)']=df_grid['r2']/(df_grid['param_motif_length'].apply(float).apply(np.sqrt))
df_grid['std/sqrt(length)']=df_grid['std_test_score']/(df_grid['param_motif_length'].apply(float).apply(np.sqrt))
df_grid.plot(kind='scatter', x='param_motif_length', y='r2/sqrt(length)',yerr='std/sqrt(length)', figsize=(5,3)).set_xticks(param_grid["motif_length"])
plt.show()
best_index=df_grid['r2/sqrt(length)'].idxmax()
CORE_MOTIF_LENGTH=df_grid.loc[best_index, 'param_motif_length']
print(f'I: The maximum ({CORE_MOTIF_LENGTH}) is suggested as CORE_MOTIF_LENGTH')
print('I: motif obtained with the best estimator from gridCV search')
# print & display results from best estimator
model_grid=grid_search.best_estimator_
model_grid.analyse_motif(X_subset,y_subset, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('best grid', model_grid)
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
Fitting 5 folds for each of 6 candidates, totalling 30 fits I: GridSearchCV took 1.41 hours for 6 candidate parameter settings. I: number of samples: 1000 I: Plot of r2 vs motif length and vs root(motif length)
I: The maximum (8) is suggested as CORE_MOTIF_LENGTH I: motif obtained with the best estimator from gridCV search I: energy matrix and logos:
A C G T
0 -8695 3711 5404 -420
1 -6270 5634 -2266 2902
2 5788 -11474 6184 -498
3 1503 3957 -6287 826
4 11595 9556 -13882 -7270
5 -978 1574 337 -933
6 -107 -345 658 -204
7 -192 1132 22 -961
I: summed absolute energies of each position:
0 18232
1 17074
2 23946
3 12574
4 42304
5 3824
6 1316
7 2309
dtype: int64
I: averaged summed energy over all positions: 15197
I: Mean and Standard Deviation for the Free Energy G to all subsequences of all probes: 1698 +/- 15663
I: Plot of the Occupancy of a subsite as the function of the Free Energy G
overlaid with the distribution of the Free Energy of all subsites.
I: There shall be only a small overlap of both curves. i.e. only the most negative Free Energies
lead to a measurable occupancy.
I: Calculated occupancy over all subsite of a single probe: binding: 0.00019 .. 1.78969 (ratio: 9486.8) I: number of probes: 1000 I: Pearson Correlation r: 0.7919 I: mean absolute error: 6779.7427
I: Classification performance AUROC: 0.8850
| stage | protein | # probes | motif length | r | AUROC | G0 | G0 fitted | ratio | max binding | min binding | energies | model | logo | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | quick | Klf9 | 1000 | 3 | 0.527776 | 0.720653 | -11473.366709 | False | 10.121019 | 0.678154 | 0.067004 | -15451,.. | suppressed | |
| 1 | best grid | Klf9 | 1000 | 8 | 0.791868 | 0.885009 | 3085.476013 | False | 9486.823691 | 1.789690 | 0.000189 | -8695,.. | suppressed |
### run a number of identical optimizations with motif length found during grid search
### goal: find best motif through repetition, judge stabiltiy of optimization
#CORE_MOTIF_LENGTH=5 # adjust core motif length if needed, motif length can be changed later
# prepare for ipyparallel
number_of_optimizations = 20
model_list = [mf.findmotif(motif_length=CORE_MOTIF_LENGTH, protein_conc=PROT_CONC, both_strands=BOTH_STRANDS)] * number_of_optimizations
X_list = [X_subset] * number_of_optimizations
y_list = [y_subset] * number_of_optimizations
def single_job(model, X, y):
model.fit(X, y)
return {'model':model}
# run the optimizations on ipp.cluster
start = time()
with ipp.Cluster(log_level=40) as rc:
rc[:].use_pickle()
view = rc.load_balanced_view()
asyncresult = view.map_async(single_job, model_list, X_list, y_list)
asyncresult.wait_interactive()
result = asyncresult.get()
print("I: Optimization took %.2f hours." % ((time() - start) / 3600))
# assemble results and analyze
df_repetitions=pd.DataFrame(result)
df_repetitions['r (subset)']=df_repetitions['model'].apply(lambda e: e.rvalue)
df_repetitions['r (train)']=df_repetitions['model'].apply(lambda e: mf.linregress(e.predict(X_train),y_train).rvalue)
df_repetitions['r (test)']=df_repetitions['model'].apply(lambda e: mf.linregress(e.predict(X_test),y_test).rvalue)
df_repetitions['G0']=df_repetitions['model'].apply(lambda e: e.finalG0_)
df_repetitions['max binding']=df_repetitions['model'].apply(lambda e: e.max_binding_fit)
df_repetitions['min binding']=df_repetitions['model'].apply(lambda e: e.min_binding_fit)
df_repetitions['ratio'] = df_repetitions['model'].apply(lambda e: e.ratio)
df_repetitions['energies']=df_repetitions['model'].apply(lambda e: e.energies_)
#df_repetitions['information']=df_repetitions['model'].apply(lambda e: mf.energies2information(e.energies_))
# display results of the ensemble of optimizations
print('I: Results of the repeated motif finding, sorted according to the regression coefficient with the train dataset')
df_repetitions.sort_values('r (train)', ascending=False, inplace=True)
mf.display_df(df_repetitions, nuc_type=NUC_TYPE)
0%| | 0/16 [00:00<?, ?engine/s]
single_job: 0%| | 0/20 [00:00<?, ?tasks/s]
I: Optimization took 0.97 hours. I: Results of the repeated motif finding, sorted according to the regression coefficient with the train dataset
| model | r (subset) | r (train) | r (test) | G0 | max binding | min binding | ratio | energies | logo | |
|---|---|---|---|---|---|---|---|---|---|---|
| 16 | suppressed | 0.886036 | 0.753992 | 0.765712 | 3085.476013 | 0.539078 | 0.000099 | 5429.581457 | -803,.. | |
| 0 | suppressed | 0.870561 | 0.753016 | 0.760949 | 3085.476013 | 0.853888 | 0.000134 | 6364.118907 | -968,.. | |
| 2 | suppressed | 0.872734 | 0.743548 | 0.764665 | 3085.476013 | 1.000380 | 0.000123 | 8121.875642 | 709,.. | |
| 12 | suppressed | 0.872361 | 0.742599 | 0.763691 | 3085.476013 | 0.792200 | 0.000180 | 4396.883533 | 536,.. | |
| 15 | suppressed | 0.872171 | 0.742351 | 0.763991 | 3085.476013 | 0.945555 | 0.000034 | 27544.090179 | 737,.. | |
| 1 | suppressed | 0.872266 | 0.742338 | 0.764172 | 3085.476013 | 0.921576 | 0.000057 | 16202.467420 | 604,.. | |
| 9 | suppressed | 0.871816 | 0.741203 | 0.762685 | 3085.476013 | 0.934662 | 0.000080 | 11635.921264 | 556,.. | |
| 18 | suppressed | 0.872099 | 0.740746 | 0.763117 | 3085.476013 | 0.933755 | 0.000097 | 9578.458210 | 778,.. | |
| 17 | suppressed | 0.871290 | 0.740542 | 0.760765 | 3085.476013 | 0.770541 | 0.000326 | 2365.986781 | 621,.. | |
| 6 | suppressed | 0.867937 | 0.738625 | 0.760049 | 3085.476013 | 0.863910 | 0.000102 | 8434.655988 | -2441,.. | |
| 5 | suppressed | 0.872236 | 0.738578 | 0.759994 | 3085.476013 | 0.463461 | 0.000071 | 6548.460383 | 535,.. | |
| 10 | suppressed | 0.858290 | 0.733919 | 0.751247 | 3085.476013 | 1.044942 | 0.000098 | 10660.187465 | 8793,.. | |
| 11 | suppressed | 0.842570 | 0.728193 | 0.751873 | 3085.476013 | 0.497516 | 0.000025 | 19914.180170 | -9618,.. | |
| 19 | suppressed | 0.842480 | 0.722510 | 0.745732 | 3085.476013 | 0.421005 | 0.000022 | 18895.447036 | -7386,.. | |
| 14 | suppressed | 0.792270 | 0.542519 | 0.552038 | 3085.476013 | 1.843514 | 0.000444 | 4152.279496 | -8401,.. | |
| 4 | suppressed | 0.794535 | 0.538746 | 0.547611 | 3085.476013 | 1.929420 | 0.000396 | 4875.330142 | -8813,.. | |
| 13 | suppressed | 0.780005 | 0.493604 | 0.508688 | 3085.476013 | 1.382613 | 0.000869 | 1591.608668 | -1522,.. | |
| 8 | suppressed | 0.780314 | 0.492755 | 0.508738 | 3085.476013 | 1.443436 | 0.000388 | 3720.572172 | 567,.. | |
| 3 | suppressed | 0.766615 | 0.464542 | 0.464071 | 3085.476013 | 5.949067 | 0.000396 | 15039.269709 | -798,.. | |
| 7 | suppressed | 0.642354 | 0.317320 | 0.325259 | 3085.476013 | 1.829086 | 0.000448 | 4084.993659 | -4114,.. |
### compare energy matrices of ensemble using PCA
print('I: Histogram of the regression coefficients r obtained by repeated optimizaion with the subset.')
df_repetitions['r (subset)'].plot(kind='hist')
plt.show()
pca = PCA(n_components=2)
pca_2c=pca.fit_transform(df_repetitions['energies'].tolist())
df_repetitions[['PCA1', 'PCA2']]=pca_2c
if sum(pca.explained_variance_ratio_)<0.5:
print('W: 2-dimensional PCA explained only %i %% of variance' %(sum(pca.explained_variance_ratio_)*100))
else:
print('I: 2-dimensional PCA explained %i %% of variance.' %(sum(pca.explained_variance_ratio_)*100))
print('I: Visualization of the PCA with the regression quality vs. subset and training dataset by color.')
df_repetitions.plot(x='PCA1', y='PCA2', kind='scatter', c='r (subset)',cmap=cm.coolwarm, edgecolors='black', linewidths=0.3)
df_repetitions.plot(x='PCA1', y='PCA2', kind='scatter', c='r (train)',cmap=cm.coolwarm, edgecolors='black', linewidths=0.3)
I: Histogram of the regression coefficients r obtained by repeated optimizaion with the subset.
I: 2-dimensional PCA explained 58 % of variance. I: Visualization of the PCA with the regression quality vs. subset and training dataset by color.
/home/GLipps/.local/lib/python3.8/site-packages/sklearn/utils/deprecation.py:101: FutureWarning: Attribute `n_features_` was deprecated in version 1.2 and will be removed in 1.4. Use `n_features_in_` instead. warnings.warn(msg, category=FutureWarning)
<matplotlib.axes._subplots.AxesSubplot at 0x7fb307785400>
# visualisation of the motif with the highest r with the train dataset
print('I: Best motif according to r (train) from the repeated optimizations.')
print('I: PCA components: %i, %i' %(df_repetitions.iloc[0]['PCA1'], df_repetitions.iloc[0]['PCA2']))
model_best_repetition=df_repetitions.iloc[0]['model']
model_best_repetition.analyse_motif(X_subset,y_subset, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('best repetition', model_best_repetition, new_entries={'r (test)': mf.linregress(model_best_repetition.predict(X_test),y_test).rvalue})
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
I: Best motif according to r (train) from the repeated optimizations. I: PCA components: -9122, 26091 I: energy matrix and logos:
A C G T
0 -803 -104 191 716
1 353 310 1798 -2462
2 -12641 14598 6282 -8238
3 -4162 2514 -2482 4130
4 1176 -8364 9691 -2503
5 -785 5587 -4258 -543
6 8667 4426 -8137 -4956
7 -531 732 419 -620
I: summed absolute energies of each position:
0 1816
1 4924
2 41761
3 13291
4 21735
5 11174
6 26188
7 2303
dtype: int64
I: averaged summed energy over all positions: 15399
I: Mean and Standard Deviation for the Free Energy G to all subsequences of all probes: 2425 +/- 15600
I: Plot of the Occupancy of a subsite as the function of the Free Energy G
overlaid with the distribution of the Free Energy of all subsites.
I: There shall be only a small overlap of both curves. i.e. only the most negative Free Energies
lead to a measurable occupancy.
I: Calculated occupancy over all subsite of a single probe: binding: 0.00010 .. 0.53908 (ratio: 5429.6) I: number of probes: 1000 I: Pearson Correlation r: 0.8860 I: mean absolute error: 4897.7168
I: Classification performance AUROC: 0.9372
| stage | protein | # probes | motif length | r | AUROC | G0 | G0 fitted | ratio | max binding | min binding | energies | model | logo | r (test) | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | quick | Klf9 | 1000 | 3 | 0.527776 | 0.720653 | -11473.366709 | False | 10.121019 | 0.678154 | 0.067004 | -15451,.. | suppressed | NaN | |
| 1 | best grid | Klf9 | 1000 | 8 | 0.791868 | 0.885009 | 3085.476013 | False | 9486.823691 | 1.789690 | 0.000189 | -8695,.. | suppressed | NaN | |
| 2 | best repetition | Klf9 | 1000 | 8 | 0.886036 | 0.937161 | 3085.476013 | False | 5429.581457 | 0.539078 | 0.000099 | -803,.. | suppressed | 0.765712 |
### motif finding on complete training dataset starting with best motif from repetitions
#fit & predict optimization starting with previous energy matrix
model_train=mf.findmotif(motif_length=CORE_MOTIF_LENGTH, protein_conc=PROT_CONC, both_strands=BOTH_STRANDS,
start=model_best_repetition.energies_)
start = time()
model_train.fit(X_train,y_train)
print("I: Optimization took %.2f hours." % ((time() - start)/3600))
# print & display main results
model_train.analyse_motif(X_train,y_train, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('train dataset', model_train, new_entries={'r (test)': mf.linregress(model_train.predict(X_test),y_test).rvalue})
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
I: Optimization took 12.61 hours. I: energy matrix and logos:
A C G T
0 -1250 234 45 969
1 1236 632 2870 -4738
2 -11633 9581 6423 -4371
3 -6211 2924 -3311 6598
4 1731 -8714 5776 1207
5 871 3729 -5446 846
6 5120 1810 -6185 -745
7 -435 1269 499 -1333
I: summed absolute energies of each position:
0 2501
1 9477
2 32010
3 19045
4 17429
5 10893
6 13861
7 3538
dtype: int64
I: averaged summed energy over all positions: 13594
I: Mean and Standard Deviation for the Free Energy G to all subsequences of all probes: 1859 +/- 12872
I: Plot of the Occupancy of a subsite as the function of the Free Energy G
overlaid with the distribution of the Free Energy of all subsites.
I: There shall be only a small overlap of both curves. i.e. only the most negative Free Energies
lead to a measurable occupancy.
I: Calculated occupancy over all subsite of a single probe: binding: 0.00004 .. 1.58737 (ratio: 43208.5) I: number of probes: 32264 I: Pearson Correlation r: 0.8035 I: mean absolute error: 2043.4959
I: Classification performance AUROC: 0.9909
| stage | protein | # probes | motif length | r | AUROC | G0 | G0 fitted | ratio | max binding | min binding | energies | model | logo | r (test) | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | quick | Klf9 | 1000 | 3 | 0.527776 | 0.720653 | -11473.366709 | False | 10.121019 | 0.678154 | 0.067004 | -15451,.. | suppressed | NaN | |
| 1 | best grid | Klf9 | 1000 | 8 | 0.791868 | 0.885009 | 3085.476013 | False | 9486.823691 | 1.789690 | 0.000189 | -8695,.. | suppressed | NaN | |
| 2 | best repetition | Klf9 | 1000 | 8 | 0.886036 | 0.937161 | 3085.476013 | False | 5429.581457 | 0.539078 | 0.000099 | -803,.. | suppressed | 0.765712 | |
| 3 | train dataset | Klf9 | 32264 | 8 | 0.803464 | 0.990876 | 3085.476013 | False | 43208.465451 | 1.587371 | 0.000037 | -1250,.. | suppressed | 0.818591 |
### Based on the motif of CORE_MOTIF_LENGTH analyze the neigbouring positions
### whether their inclusion can improve the quality of the motif
df_positions=model_train.investigate_extension_parallel(X_train,y_train, end5=3, end3=3, nuc_type=NUC_TYPE)
list_positions=df_positions.index[df_positions['+2%']].tolist()+[0] # list of positions with an increase of2% and default position 0
ext5=-min(list_positions)
ext3=max(list_positions)
print("I: It is suggested to extend the core motif at the 5' end by %i and at the 3' end by %i positions." %(ext5, ext3))
### Analyze model whether the estimated G0 is correct
df_G0=model_train.investigate_G0(X_train,y_train)
0%| | 0/6 [00:00<?, ?engine/s]
job5: 0%| | 0/3 [00:00<?, ?tasks/s]
job3: 0%| | 0/3 [00:00<?, ?tasks/s]
I: Optimization took 0.35 hours.
I: It is suggested to extend the core motif at the 5' end by 2 and at the 3' end by 0 positions. I: Current G0 = 3085 J/mol (see red broken line in figure below) with r = 0.803. I: Maximal r is 0.803 at G0=3085 J/mol (see green broken line below). I: Maximal occupancy of 2 is reached at G0=1085 J/mol (see blue broken line below). I: Maximal occupancy of 0.2 is reached at G0=11085 J/mol (see blue broken line below).
I: G0 is in a range leading to maximal probe occupancy between 0.2 and 2. Good. I: Current G0 is close to the G0 leading to maximal r. Good.
### fit & predict optimization starting with extended energy matrix if extension appears to improve prediction
if ext5+ext3!=0: #extension suggestion from previous analysis of the bordering positions
expanded_energies=model_train.energies_
# append energies of single-optimized bordering positions to energies of central part
if ext5!=0:
energies_5=np.concatenate(df_positions['energies'][(df_positions.index<0) & (df_positions.index>=-ext5)].to_numpy())
expanded_energies=np.concatenate((energies_5, expanded_energies))
if ext3!=0:
energies_3=np.concatenate(df_positions['energies'][(df_positions.index<=ext3) & (df_positions.index>0)].to_numpy().flatten())
expanded_energies=np.concatenate((expanded_energies, energies_3))
mf.energies2logo(expanded_energies, nuc_type=NUC_TYPE)
print('I: Optimization started with extended motif.')
expanded_motif_length=len(expanded_energies)//4
model_extended=mf.findmotif(motif_length=expanded_motif_length, protein_conc=PROT_CONC, both_strands=BOTH_STRANDS,
start=expanded_energies)
start = time()
model_extended.fit(X_train,y_train)
print("Optimization took %.2f hours." % ((time() - start)/3600))
# print & display main results
model_extended.analyse_motif(X_train,y_train, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('train, extended', model_extended, new_entries={'r (test)': mf.linregress(model_extended.predict(X_test),y_test).rvalue})
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
else:
model_extended=model_train
print('I: Motif is not extended based on previous analysis.')
I: Optimization started with extended motif. Optimization took 10.91 hours. I: energy matrix and logos:
A C G T
0 -1189 1185 -225 229
1 -303 268 239 -204
2 -1196 255 77 862
3 1160 705 2827 -4692
4 -14656 15737 6434 -7515
5 -6670 2697 -3794 7767
6 1199 -9639 8109 330
7 699 3777 -5481 1004
8 4391 2379 -6098 -672
9 -469 1263 576 -1370
I: summed absolute energies of each position:
0 2830
1 1015
2 2392
3 9385
4 44345
5 20929
6 19278
7 10962
8 13542
9 3679
dtype: int64
I: averaged summed energy over all positions: 12836
I: Mean and Standard Deviation for the Free Energy G to all subsequences of all probes: 3915 +/- 16300
I: Plot of the Occupancy of a subsite as the function of the Free Energy G
overlaid with the distribution of the Free Energy of all subsites.
I: There shall be only a small overlap of both curves. i.e. only the most negative Free Energies
lead to a measurable occupancy.
I: Calculated occupancy over all subsite of a single probe: binding: 0.00001 .. 1.61221 (ratio: 147258.8) I: number of probes: 32264 I: Pearson Correlation r: 0.8352 I: mean absolute error: 1943.9151
I: Classification performance AUROC: 0.9931
| stage | protein | # probes | motif length | r | AUROC | G0 | G0 fitted | ratio | max binding | min binding | energies | model | logo | r (test) | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | quick | Klf9 | 1000 | 3 | 0.527776 | 0.720653 | -11473.366709 | False | 10.121019 | 0.678154 | 0.067004 | -15451,.. | suppressed | NaN | |
| 1 | best grid | Klf9 | 1000 | 8 | 0.791868 | 0.885009 | 3085.476013 | False | 9486.823691 | 1.789690 | 0.000189 | -8695,.. | suppressed | NaN | |
| 2 | best repetition | Klf9 | 1000 | 8 | 0.886036 | 0.937161 | 3085.476013 | False | 5429.581457 | 0.539078 | 0.000099 | -803,.. | suppressed | 0.765712 | |
| 3 | train dataset | Klf9 | 32264 | 8 | 0.803464 | 0.990876 | 3085.476013 | False | 43208.465451 | 1.587371 | 0.000037 | -1250,.. | suppressed | 0.818591 | |
| 4 | train, extended | Klf9 | 32264 | 10 | 0.835230 | 0.993097 | 7518.696033 | False | 147258.814946 | 1.612210 | 0.000011 | -1189,.. | suppressed | 0.852736 |
### fit & predict optimization starting with extended energy matrix plus one bordering position on each side if current bordering position exceed the information of 0.25
I_5=mf.energies2information(model_extended.energies_[0:4])>=0.25 #sufficient information content of 5' end position
I_3=mf.energies2information(model_extended.energies_[-4:])>=0.25 #sufficient information content of 3' end position
if I_5 or I_3:
print('I: At least one of the bordering positions has an information content of at least 0.25. Extending.')
expanded_energies_with_border=mf.modify_energies(model_extended.energies_, end5=I_5, end3=I_3)
mf.energies2logo(expanded_energies_with_border, nuc_type=NUC_TYPE)
motif_length_with_border=len(expanded_energies_with_border)//4
model_with_border=mf.findmotif(motif_length=motif_length_with_border, protein_conc=PROT_CONC, both_strands=BOTH_STRANDS,
start=expanded_energies_with_border)
start = time()
model_with_border.fit(X_train,y_train)
print("Optimization took %.2f hours." % ((time() - start)/3600))
# print & display main results
model_with_border.analyse_motif(X_train,y_train, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('train, expanded, border', model_with_border, new_entries={'r (test)': mf.linregress(model_with_border.predict(X_test),y_test).rvalue})
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)
else:
print('I: Both bordering positions of the found motif have an information content below 0.25. No futher optimization required.')
I: Both bordering positions of the found motif have an information content below 0.25. No futher optimization required.
### Analyze model whether the estimated G0 is correct
df_G0=model_extended.investigate_G0(X_train,y_train)
I: Current G0 = 7519 J/mol (see red broken line in figure below) with r = 0.835. I: Maximal r is 0.835 at G0=7519 J/mol (see green broken line below). I: Maximal occupancy of 2 is reached at G0=5519 J/mol (see blue broken line below). I: Maximal occupancy of 0.2 is reached at G0=15519 J/mol (see blue broken line below).
I: G0 is in a range leading to maximal probe occupancy between 0.2 and 2. Good. I: Current G0 is close to the G0 leading to maximal r. Good.
STAGES.df.to_json('%s_%s-%s-%s_%s-%s.json' %(PROTEIN_NAME, datetime.now().year, datetime.now().month,datetime.now().day , datetime.now().hour, datetime.now().minute))
STAGES.df.to_pickle('%s_%s-%s-%s_%s-%s.pkl' %(PROTEIN_NAME, datetime.now().year, datetime.now().month,datetime.now().day , datetime.now().hour, datetime.now().minute))
mf.energies2logo(mf.reverse_complement(STAGES.df.at[3,'energies']), nuc_type=NUC_TYPE)
| A | C | G | T | |
|---|---|---|---|---|
| 0 | -1333.569624 | 499.448110 | 1269.897878 | -435.776364 |
| 1 | -745.014775 | -6185.798662 | 1810.582895 | 5120.230543 |
| 2 | 846.068567 | -5446.563692 | 3729.124107 | 871.371018 |
| 3 | 1207.567928 | 5776.085161 | -8714.665334 | 1731.012245 |
| 4 | 6598.554401 | -3311.284649 | 2924.250189 | -6211.519941 |
| 5 | -4371.331301 | 6423.285490 | 9581.939541 | -11633.893730 |
| 6 | -4738.970386 | 2870.539792 | 632.293995 | 1236.136599 |
| 7 | 969.831012 | 45.818567 | 234.947275 | -1250.596854 |
"""
expanded_energies=mf.modify_energies(model_train.energies_, end5=ext5, end3=ext3) # <==== adjust end5 and end3 to enlarge core motif on 5' and 3' end
mf.energies2logo(expanded_energies, nuc_type=NUC_TYPE)
expanded_motif_length=len(expanded_energies)//4
"""
df_stages.drop(index='best grid fitG0=True', inplace=True)
import importlib
importlib.reload(mf)
start = time()
model_mae=model_with_border.refit_mae(X,y)
print("Optimization took %.2f hours." % ((time() - start)/3600))
# print & display main results
model_mae.analyse_motif(X_train,y_train, THRESHOLD, nuc_type=NUC_TYPE)
# store results and display stages
STAGES.append('train, expanded, border, mae', model_mae, new_entries={'r (test)': mf.linregress(model_mae.predict(X_test),y_test).rvalue})
mf.display_df(STAGES.df, nuc_type=NUC_TYPE)